package com.zhonghui.common.util;


import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class JwtToken {
    /**
     * 除 第一个写的 static map 之外 其他都是 static String
     */
    private static String jwtKey;
    private static Integer expiredTimeIn;
    private static Integer defaultScope = 8;

    @Value("${eshop.security.jwt-key}")
    public void setJwtKey(String jwtKey){
        JwtToken.jwtKey = jwtKey;
    }

    @Value(("${eshop.security.token-expired-in}"))
    public void setExpiredTimeIn(Integer expiredTimeIn){ JwtToken.expiredTimeIn = expiredTimeIn;
    }

    public static Boolean verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            return false;
        }
        return true;
    }


    public static String getExpireTime(String token){
        return DateUtil.formatDateTime(JWT.decode(token).getExpiresAt());
    }

    public static String makeToken(Long uid,String uName,Integer scope){
        return JwtToken.getToken(uid,uName,scope);
    }

    public static String makeToken(Long uid,String uName){
        return JwtToken.getToken(uid,uName,JwtToken.defaultScope);
    }

    public static String getToken(Long uid,String uName,Integer scope){
        Algorithm algorithm = Algorithm.HMAC256(JwtToken.jwtKey);
        Map<String, Date> map =JwtToken.calculateExpiredIssues();
        return JWT.create()
                .withClaim("uid",uid)
                .withClaim("uName",uName)
                .withClaim("scope",scope)
                .withExpiresAt(map.get("expiredTime"))
                .withIssuedAt(map.get("now"))
                .sign(algorithm);
    }


    public static Map<String,Date> calculateExpiredIssues(){
        Map<String, Date> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();

        Date now = calendar.getTime();
        calendar.add(Calendar.SECOND, JwtToken.expiredTimeIn);

        map.put("now",now);
        map.put("expiredTime",calendar.getTime());

        return map;
    }
}
